<template>
	<div class="allcontent">
		<div class="search">
			<el-form @submit.native.prevent ref="queryRef" :model="searchParam">
				<el-row gutter="10">
					<el-col span="5">
						<el-form-item prop="roleName">
							<el-input  size="default"  @keyup.enter.native="search" placeholder="请输入角色名称模糊搜索" autofocus v-model="searchParam.roleName"></el-input>
						</el-form-item>
					</el-col>
					<el-col  span="5">
						<el-form-item prop="roleMark">
							<el-input  size="default"   @keyup.enter.native="search" placeholder="请输入角色标识模糊搜索"  v-model="searchParam.roleMark"></el-input>
						</el-form-item>
					</el-col>
					<el-col  span="5">
						<el-select  size="default"  @change="search" v-model="searchParam.status" style="width:200px" placeholder="请选择状态搜索">
						    <el-option
						      key="-1"
						      label="全部"
						      value="-1"
						    />
							<el-option
						      key="1"
						      label="正常"
						      value="1"
						    />
							<el-option
							  key="0"
							  label="禁用"
							  value="0"
							/>
						</el-select>
					</el-col>
					<el-col  span="5">
						<el-button round  size="default"   plain icon="Search" type="primary" @click="search">搜索</el-button>
					</el-col>
					<el-col  span="4">
						<el-button round  size="default"  plain icon="Refresh" type="warning" @click="reset(queryRef)">重置</el-button>
					</el-col>
				</el-row>
				<el-row gutter="10" style="margin-top:10px;margin-bottom: 10px;">
					<el-col span="8">
						<el-button round  size="default"   plain icon="Edit"  v-if="userStore.hasPermission('system:role:add')" type="success" @click="addRole()">新增</el-button>
					</el-col>
					<el-col span="8">
						<el-button round  size="default"   plain icon="Edit" v-if="userStore.hasPermission('system:role:edit')" type="primary" @click="editRole()"  :disabled="selections.length > 1||  selections.length == 0?true:false">编辑</el-button>
					</el-col>
					<el-col span="8">
						<el-popconfirm
						  v-if="userStore.hasPermission('system:role:delete')"
						    confirm-button-text="确认"
						    cancel-button-text="取消"
						    :icon="InfoFilled"
						    icon-color="#626AEF"
						    title="是否确认删除这些数据？"
						    @confirm="removeRole()"
						  >
						    <template #reference>
						      <el-button round  size="default"  plain icon="Delete" :disabled="selections.length == 0?true:false"  type="danger" >删除</el-button>
						    </template>
						</el-popconfirm>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<div class="el-table">
			<el-table ref="tableRef"  :data="tableData" style="width: 100%;font-size:13px;"  v-loading="loading" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55"  :selectable="selectData"></el-table-column>
			    <el-table-column prop="roleName" label="角色名称"/>
			    <el-table-column prop="roleMark" label="角色标识"/>
				<el-table-column prop="status" label="状态">
					<template  #default="scope">
						<el-tag v-if="scope.row.status == 1">正常</el-tag>
						<el-tag type="danger" v-else-if="scope.row.status == 0">禁用</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="sort" label="排序"/>
				<el-table-column  label="操作"  width="450" >
					<template  #default="scope">
						<el-button round  plain icon="Edit"   v-if="userStore.hasPermission('system:role:edit')" size="default" type="primary" @click="editRole(scope.row.id)">编辑</el-button>
						<el-popconfirm
						  v-if="userStore.hasPermission('system:role:delete') && scope.row.roleName != '管理员'"
						    confirm-button-text="是"
						    cancel-button-text="否"
						    :icon="InfoFilled"
						    icon-color="#626AEF"
						    title="是否删除该数据?"
						    @confirm="removeRole(scope.row.id)"
						  >
						    <template #reference>
						      <el-button round  plain icon="Delete"  size="default" type="danger" v-if="scope.row.roleName != '管理员'">
								  删除
						      </el-button>
						    </template>
						  </el-popconfirm>
						<el-button round plain icon="Operation" v-if="userStore.hasPermission('system:role:assignPermission')"   size="default" type="success" @click="assignPermissions(scope.row.id)">分配权限</el-button>
						<el-button round  plain icon="Operation" v-if="userStore.hasPermission('system:user:assignUserPage')"  size="default" type="warning" @click="assignUser(scope.row)">分配用户</el-button>
						
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="el-pager">
		   <el-pagination layout="total,sizes,prev, pager, next,jumper" :total="total" 
		   :page-sizes="[10,20,30,40,50]" :pager-count="11"
		   size="default"  background  class="mt-4" :current-page="currentPage"
		   @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
		</div>
		<el-drawer size="40%" v-model="addRoleDialog" title="新增" width="50%">
			<AddRole  @closeAddRoleForm="closeAddRoleForm" @success="success"></AddRole>
		</el-drawer>
		<el-drawer  size="40%" v-model="editRoleDialog" title="编辑" width="50%">
			<EditRole :roleId="roleId"  @closeEditRoleForm="closeEditRoleForm" @success="success"></EditRole>
		</el-drawer>
		<el-drawer  size="40%" v-model="assignPermissionsDialog" title="分配权限" width="50%">
			<AssignPermissions :roleId="roleId"  @closeAssignPermissionsForm="closeAssignPermissionsForm" @success="success"></AssignPermissions>
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
	import {ref,reactive,onMounted} from 'vue'
	import AddRole from './AddRole.vue'
	import EditRole from './EditRole.vue'
	import AssignPermissions from './AssignPermissions.vue'
	import type { FormInstance, FormRules } from 'element-plus'
	import {ElMessage} from 'element-plus'
	import {useRouteStore} from '@/stores/route.ts'
	import {page,remove} from '@/api/role.ts'
	import {useUserStore} from '@/stores/user.ts'
  import {InfoFilled} from "@element-plus/icons-vue";
	const useRoute = useRouteStore();
	const router = useRoute.router;
	const userStore = useUserStore()
	
	const selectData=(row: any, index: number)=>{
		if(row.roleName === '管理员'){
			return false;
		}
		return true;
	}
	
	const searchParam =reactive({
		username:null,
		phone:null,
		status:null,
		page:1,
		limit:10,
	})
	const search=()=>{
		console.log("好的")
		loadData(searchParam);
	}
	const queryRef=ref<FormInstance>();
	const reset = (formEl: FormInstance | undefined) => {
		  if (!formEl) return
		  formEl.resetFields()
		  loadData();
	}
	
	const tableData = ref([]);
	const total = ref(0);
	const loading=ref(false);
	const loadData =()=>{
		loading.value=true;
		page(searchParam).then((res)=>{
			if(res.code === 200){
				tableData.value = res.data.list;
				total.value = res.data.total;
			}
			loading.value=false;
		})
	}
	onMounted(()=>{
		loadData();
	})
	const currentPage = ref(1)
	const handleSizeChange = (val: number) => {
	  console.log(`${val} items per page`)
	  searchParam.limit= val;
	  loadData();
	}
	const handleCurrentChange = (val: number) => {
	  console.log(`current page: ${val}`)
	  currentPage.value= val;
	  searchParam.page= val;
	  loadData();
	}
	
	const tableRef=ref<InstanceType<typeof ElTable>>()
	const selections = ref([])
	const handleSelectionChange=(val)=>{
		selections.value=val;
	}
	
	const addRoleDialog = ref(false);
	const editRoleDialog = ref(false);
	
	// 关闭保存用户弹出框
	const closeAddRoleForm = ()=> {
	  addRoleDialog.value = false
	}
	const closeEditRoleForm = ()=> {
	  editRoleDialog.value = false
	}
	
	// 提交表单回调函数
	const success = ()=> {
	  addRoleDialog.value = false
	  editRoleDialog.value = false
	  assignPermissionsDialog.value = false;
	  loadData();
	}
	const roleInfo = ref()
	const addRole=()=>{
		addRoleDialog.value = true;
	}
	const removeRole=async (id:number)=>{
		if(selections.value.length < 0){
			ElMessage({
			  type: 'info',
			  message: '至少选择一行进行删除',
			})
			return;
		}
		let ids = [];
		if(id != undefined){
			ids.push(id);
		}else{
			selections.value.forEach((item)=>{
				ids.push(item.id)
			})
		}
		console.log("ids:"+ids)
		await remove(ids)
		loadData();
	}
	const roleId=ref();
	const editRole=(id:number)=>{
		if(id != undefined){
			roleId.value = id;
		}else if(selections.value.length > 0){
			if(selections.value.length > 1){
				ElMessage({
				  type: 'warning',
				  message: '编辑只能选择一行',
				})
				return;
			}
			roleId.value = selections.value[0].id
		}else{
			ElMessage({
			  type: 'warning',
			  message: '选择一行进行编辑',
			})
			return;
		}
		editRoleDialog.value = true;
		
	}	
	const assignPermissionsDialog = ref(false);
	const assignPermissions = (id:number)=>{
		roleId.value = id;
		assignPermissionsDialog.value = true;
	}
	const closeAssignPermissionsForm=()=>{
		assignPermissionsDialog.value = false;
	}
	const assignUser=(row:any)=>{
		router.push({path:'/assignUserList/'+row.id})
	}
</script>

<style scoped>
	.search{
		margin-bottom: 10px;
	}
  .el-pager{
    padding: 2%;
    justify-content: flex-start;
    align-items: flex-start;
    position: absolute;
    bottom:0;
    right:0;
    margin-bottom:25px;
    width: 100%;
    background-color: white;
    z-index: 1;
  }
	.allcontent{
		height: 80vh;
		position: relative;
	}
	.el-table{
		max-height:70%;
		overflow: auto;
    z-index: 0;
	}
	.el-table::-webkit-scrollbar{
		display: none;
	}
</style>